import axios from 'axios';
import config from "../config";
import signMd5Utils from "./signMd5Utils";
import {getToken, setToken} from "./auth";
import {toast} from "./common";
import {clearFileContent} from "./storageFile";

const request = (options) => {
    return new Promise(async (resolve, reject) => {
        // 动态获取最新token
        let token = getToken();
        if (!token && options.url != "sys/mLogin") {
            clearFileContent() //清空
            uni.reLaunch({url: '../login'});
            return config;
        }
        const fullUrl = options.baseUrl
            ? options.baseUrl.replace(/\/$/, '') + '/' + options.url.replace(/^\//, '')
            : options.url
        let data = {...options.data}
        console.log(fullUrl,data)
        uni.request({
            url: fullUrl,
            method: options.method || 'GET',
            data: data,
            header: {
                'Content-Type': 'application/json',
                'X-Access-Token': getToken(),
                'X-Sign': signMd5Utils.getSign(options.url, options.data), // 你的签名方法
                'X-TIMESTAMP': signMd5Utils.getTimestamp()
            },
            success: async (res) => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    if (res.data.code >= 200 && res.data.code < 300) {
                        resolve(res.data)
                    } else {
                        resolve(res.data)
                    }
                } else {
                    if (res.data.code == 401) {
                        setToken(null)//
                        clearFileContent() //清空
                        uni.reLaunch({
                            url: '../login',
                        })
                    }
                    reject(res.data)
                }
            },
            fail: (err) => {
                console.log("fail", err)
                let {message} = err
                if (err.errMsg) {
                    if (err.errMsg === 'Network Error') {
                        message = '后端接口连接异常'
                    } else if (err.errMsg.includes('timeout')) {
                        message = '系统接口请求超时'
                    } else if (err.errMsg.includes('Request failed with status code')) {
                        message = '系统接口' + message.substr(message.length - 3) + '异常'
                    } else if (err.errMsg.includes('request:fail')) {
                        message = '网络链接超时'
                    }
                }
                if (err.status == 401) {
                    console.log(err.status)
                    setToken(null)//
                    clearFileContent() //清空
                    uni.reLaunch({
                        url: '../login',
                    })
                }
                try {
                    toast(message.response || message.response.data || message.response.data.message || message)
                } catch (error) {
                    toast(message)
                }
                reject(err)
            }
        })
    })
}


// 通用的请求方法
const action = {
    get(url, params) {
        const options = {
            url: url,
            baseUrl: config.baseUrl,
            method: "GET",
            data: params
        }
        return request(options);
    },
    post(url, data) {
        const options = {
            url: url,
            baseUrl: config.baseUrl,
            method: "POST",
            data: data
        }
        return request(options);
    },
    put(url, data) {
        const options = {
            url: url,
            baseUrl: config.baseUrl,
            method: "PUT",
            data: data
        }
        return request(options);
    },
    delete(url, params) {
        const options = {
            url: url,
            baseUrl: config.baseUrl,
            method: "DELETE",
            data: params
        }
        return request(options);
    }
};


//post
export function postAction(url, parameter) {
    return action.post(url, parameter)
}

//post method= {post | put}

//put
export function putAction(url, parameter) {
    return action.put(url, parameter)
}

//get
export function getAction(url, parameter) {
    return action.get(url, parameter)
}

//deleteAction
export function deleteAction(url, parameter) {
    return action.delete(url, parameter)
}

//从缓存中获取字典配置
function getDictItemsFromCache(dictCode) {
    try {
        const dictItems = uni.getStorageSync(dictCode);
        if (dictItems) {
            return dictItems;
        }
    } catch (e) {
        return null
    }
}

/**
 * 获取字典数据
 */
export async function initDictData(dictCode, params) {
    let dictOptions = []
    //优先从缓存中读取字典配置
    if (getDictItemsFromCache(dictCode)) {
        dictOptions = getDictItemsFromCache(dictCode);
        if (dictOptions.length > 0) {
            return dictOptions
        }
    }

    //根据字典Code, 初始化字典数组
    let res = await getAction(`/sys/dict/getDictItems/${dictCode}`, params)
    if (res.success) {
        dictOptions = res.result;
        //增加缓存
        uni.setStorage({key: dictCode, data: dictOptions});
    }
    return dictOptions
}
